package com.hello.system.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.system.annotation.ContentSecurity;
import com.hello.system.service.WxContentSecurityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信小程序控制器
 * 
 * @author hello
 */
@RestController
@RequestMapping("/system/wx")
@Slf4j
public class WxMiniappController extends BaseController {

    @Autowired
    private WxMaService wxMaService;
    
    @Autowired
    private WxContentSecurityService contentSecurityService;
    
    @Value("${wx.miniapp.appid}")
    private String appId;
    
    @Value("${wx.miniapp.secret}")
    private String secret;
    
    /**
     * 小程序登录获取OpenID
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        if (code == null || code.isEmpty()) {
            return AjaxResult.error("登录失败：code不能为空");
        }
        
        try {
            log.info("小程序登录请求, code: {}", code);
            
            WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(code);
            
            Map<String, Object> data = new HashMap<>();
            data.put("openid", result.getOpenid());
            data.put("sessionKey", result.getSessionKey());
            
            log.info("小程序登录成功, openid: {}", result.getOpenid());
            return AjaxResult.success("登录成功", data);
        } catch (Exception e) {
            log.error("获取OpenID失败", e);
            return AjaxResult.error("获取OpenID失败: " + e.getMessage());
        }
    }

    /**
     * 统一的文本内容安全识别接口
     */
    @PostMapping("/checkText")
    public AjaxResult checkText(@RequestBody Map<String, String> params) {
        String content = params.get("content");
        String openid = params.get("openid");
        
        if (content == null || content.isEmpty()) {
            return AjaxResult.error("校验失败：content不能为空");
        }
        
        try {
            Map<String, Object> result = contentSecurityService.checkText(content, openid);
            
            if ((Boolean) result.get("pass")) {
                return AjaxResult.success("校验通过", result);
            } else {
                return AjaxResult.error((String) result.get("message"), result);
            }
        } catch (Exception e) {
            log.error("文本内容安全识别失败", e);
            return AjaxResult.error("文本内容安全识别失败: " + e.getMessage());
        }
    }

    /**
     * 内容安全检测测试接口
     */
    @PostMapping("/testContentSecurity")
    public AjaxResult testContentSecurity(@RequestBody Map<String, String> params) {
        String openid = params.get("openid");
        
        // 定义一系列测试文本
        String[] testContents = new String[] {
            // 微信官方文档测试用例
            "特3456书yuuo莞6543李zxcz蒜7782法fgnv级",
            "完2347全dfji试3726测asad感3847知qwez到",
            // 色情相关敏感词（使用特殊符号替代真实敏感词）
            "这里有黄**色**电影",
            "出售各种**色**情**视频",
            // 政治敏感词（使用特殊符号替代真实敏感词）
            "讨论敏感政治话题如***和***",
            // 赌博相关敏感词
            "网上****博彩****",
            "线上赌场",
            // 诈骗相关敏感词
            "免费领取**奖品**只需转发",
            "100%****中奖****的彩票"
        };
        
        Map<String, Object> results = new HashMap<>();
        
        for (String content : testContents) {
            try {
                Map<String, Object> result = contentSecurityService.checkText(content, openid);
                results.put(content, result);
            } catch (Exception e) {
                log.error("检测文本 [{}] 失败", content, e);
                results.put(content, "检测异常: " + e.getMessage());
            }
        }
        
        return AjaxResult.success("测试完成", results);
    }
    
    /**
     * 使用注解进行内容安全检测的示例接口
     */
    @PostMapping("/publishComment")
    @ContentSecurity(fieldName = "content")
    public AjaxResult publishComment(@RequestBody Map<String, String> params) {
        String content = params.get("content");
        
        if (content == null || content.isEmpty()) {
            return AjaxResult.error("发布失败：评论内容不能为空");
        }
        
        // 内容安全检测已通过AOP完成，这里只处理业务逻辑
        // 模拟成功发布评论
        Map<String, Object> result = new HashMap<>();
        result.put("commentId", System.currentTimeMillis());
        result.put("content", content);
        result.put("createdAt", System.currentTimeMillis());
        
        return AjaxResult.success("发布成功", result);
    }
} 